package database

import (
	"blog2/util"
	"fmt"
	"log"
	"os"
	"sync"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	ormlog "gorm.io/gorm/logger"
)

var (
	dblog         ormlog.Interface
	blogMysql     *gorm.DB
	blogMysqlOnce sync.Once
)

func init() {
	dblog = ormlog.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		ormlog.Config{
			SlowThreshold: 100 * time.Millisecond,
			LogLevel:      ormlog.Info,
			Colorful:      true,
		},
	)
}

func createMySqlDB(dbname, host, user, password string, port int) *gorm.DB {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, port, dbname)
	var err error
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{Logger: dblog, PrepareStmt: true})
	if err != nil {
		util.LogRus.Errorf("connect to mysql use dsn %s failed: %s", dsn, err)
	}
	sqlDB, _ := db.DB()
	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetMaxIdleConns(20)
	util.LogRus.Infof("connect to mysql db %s", dbname)
	return db
}

func GetBlogDBConnection() *gorm.DB { // 单例模式
	blogMysqlOnce.Do(func() {
		if blogMysql != nil {
			return
		}
		dbName := "blog"
		viper := util.CreateConfig("mysql")
		host := viper.GetString("blog.host")
		user := viper.GetString("blog.user")
		pass := viper.GetString("blog.pass")
		port := viper.GetInt("blog.port")
		blogMysql = createMySqlDB(dbName, host, user, pass, port)
	})

	return blogMysql
}
